const initialState = {
  commentData: {} as ICommentData,
  originComment: {} as ICommentItem,
  replyData: {} as ICommentData,
};

export type ActionType =
  | { type: 'comment/saveComments'; payload: ICommentData }
  | { type: 'comment/saveOriginComment'; payload: ICommentItem }
  | { type: 'comment/clearOriginComment' }
  | { type: 'comment/updateComments'; payload: ICommentItem }
  | { type: 'comment/saveReplyComment'; payload: ICommentData }
  | { type: 'comment/clearReplyComment' };

function commentReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'comment/saveComments':
      return {
        ...state,
        commentData: action.payload,
      };
    case 'comment/saveOriginComment':
      return {
        ...state,
        originComment: action.payload,
      };
    case 'comment/clearOriginComment':
      return {
        ...state,
        originComment: {} as ICommentItem,
      };
    case 'comment/updateComments':
      return {
        ...state,
        commentData: {
          ...state.commentData,
          total_count: state.commentData.total_count + 1,
          results: [action.payload, ...state.commentData.results],
        },
      };
    case 'comment/saveReplyComment':
      return {
        ...state,
        replyData: action.payload,
      };

    case 'comment/clearReplyComment':
      return {
        ...state,
        replyData: {} as ICommentData,
      };

    default:
      return state;
  }
}

export default commentReducer;

interface ICommentData {
  total_count: number;
  end_id: string;
  last_id: string;
  results: ICommentItem[];
}

export interface ICommentItem {
  com_id: string;
  content: string;
  reply_count: number;
  pubdate: string;
  is_followed: boolean;
  is_liking: boolean;
  like_count: number;
  aut_id: string;
  aut_name: string;
  aut_photo: string;
}
